package com.caipos.service;

import com.caipos.entity.Device;
import com.caipos.repository.jpa.DeviceJpaRepository;
import com.caipos.repository.redis.DeviceRedisRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class DeviceService {

    private final DeviceJpaRepository deviceJpaRepository;
    private final DeviceRedisRepository deviceRedisRepository;

    /**
     * 注册新设备
     */
    @Transactional
    public Device registerDevice(Device device) {
        // 检查设备是否已存在
        if (deviceJpaRepository.existsByDeviceId(device.getDeviceId())) {
            throw new IllegalArgumentException("Device with ID " + device.getDeviceId() + " already exists");
        }
        
        // 保存到数据库
        Device savedDevice = deviceJpaRepository.save(device);
        // 更新缓存
        deviceRedisRepository.save(savedDevice);
        return savedDevice;
    }

    /**
     * 根据设备ID查询设备
     */
    public Optional<Device> getDeviceByDeviceId(String deviceId) {
        // 先从缓存查询
        Optional<Device> cachedDevice = Optional.ofNullable(deviceRedisRepository.findById(deviceId).orElse(null));
        if (cachedDevice.isPresent()) {
            return cachedDevice;
        }
        
        // 缓存未命中则从数据库查询，并更新缓存
        Optional<Device> dbDevice = deviceJpaRepository.findByDeviceId(deviceId);
        dbDevice.ifPresent(deviceRedisRepository::save);
        return dbDevice;
    }

    /**
     * 获取所有设备
     */
    public List<Device> getAllDevices() {
        return deviceJpaRepository.findAll();
    }

    /**
     * 更新设备状态
     */
    @Transactional
    public void updateDeviceStatus(String deviceId, String status) {
        getDeviceByDeviceId(deviceId).ifPresent(device -> {
            device.setStatus(status);
            device.setLastHeartbeat(LocalDateTime.now());
            deviceJpaRepository.save(device);
            deviceRedisRepository.save(device);
        });
    }

    /**
     * 更新设备连接信息
     */
    @Transactional
    public void updateDeviceConnection(String deviceId, String ipAddress, int port) {
        getDeviceByDeviceId(deviceId).ifPresent(device -> {
            device.setIpAddress(ipAddress);
            device.setPort(port);
            device.setLastHeartbeat(LocalDateTime.now());
            device.setStatus("ONLINE");
            deviceJpaRepository.save(device);
            deviceRedisRepository.save(device);
        });
    }

    /**
     * 检查设备是否已存在
     */
    public boolean deviceExists(String deviceId) {
        return deviceJpaRepository.existsByDeviceId(deviceId);
    }
}
    